# -*- coding: utf-8 -*-
import time
import os
import tornado
import uuid
import json
# import oss2
import logging
# import PILImageMy as mypil
from u_2_net import my_u2net_test
from to_background import to_background
from to_background import to_standard_trimap
from m_dlib import crop
import globalvar as gl
import random

logging.basicConfig(
    level=logging.ERROR,#控制台打印的日志级别
    filename='./logs/error.log',
    filemode='a',##模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志 #a是追加模式，默认如果不写的话，就是追加模式
    format= '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' #日志格式
)
logging.info('start logging')
# auth = oss2.Auth('LTAI0MUr7yKRgtyq', 'Rkc1gU4fUdCHxlc8OwkaFGadRcyLOl')
# bucket = oss2.Bucket(auth, 'http://oss-cn-shanghai.aliyuncs.com', 'xgt2016')

class UploadHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Content-type", "application/json; charset=utf-8")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

    def post(self, *args, **kwargs):
        starttime = time.time()
        # 查看上传文件的完整格式，files以字典形式返回
        # print(os.path.dirname(__file__))
        # print(self.request.files)
        # {'crop_file':
        # [{'filename': 'test.jpg', 'body': b'61 60 -83\r\n-445 64 -259', 'content_type': 'text/plain'}],
        # 'file2':
        if len(self.request.files['crop_file']) == 0:
            self.send_error(500, msg="没有上传文件!")
            return
        color = self.get_argument('color', 'white')
        solve_type = self.get_argument('solve_type', 'quality')
        shortuuid = str(uuid.uuid1())
        fileName = shortuuid + '_' + self.request.files['crop_file'][0]['filename']
        parent_path = os.path.dirname(__file__)
        org_img = os.path.join(parent_path, "static/img", fileName+".jpg")
        fileBody = self.request.files['crop_file'][0]['body']
        with open(org_img, 'wb') as f:
            f.write(fileBody)

        # 图片裁剪
        print('准备时间:', time.time() - starttime)
        starttime = time.time()
        id_image = os.path.join(parent_path, "static/img", fileName+"_test_id.png")
        # 通过识别人脸关键点，裁剪图像
        crop.crop_photo(org_img,id_image,solve_type)

        print('剪裁时间:', time.time() - starttime)
        starttime = time.time()
        alpha_img = os.path.join(parent_path, "static/img", fileName+"_alpha.png")
        alpha_resize_img = os.path.join(parent_path, "static/img", fileName+"_alpha_resize.png")
        trimap = os.path.join(parent_path, "static/img", fileName+"_trimap_resize.png")
        id_image_org = os.path.join(parent_path, "static/img", fileName+"_test_id_1in.png")
        #
        # 通过u_2_net 获取 alpha
        my_u2net_test.test_seg_trimap(id_image, alpha_img, alpha_resize_img)
        print('alpha时间:', time.time() - starttime)
        starttime = time.time()
        #
        # # 通过alpha 获取 trimap
        to_standard_trimap.to_standard_trimap(alpha_resize_img, trimap)
        print('trimap时间:', time.time() - starttime)
        starttime = time.time()
        #
        # 证件照添加蓝底纯色背景
        to_background.to_background(id_image, trimap, id_image_org, color)
        if time.time() > 1659139200:
            wrong = (time.time() - gl.get_value("runningtime")) / (3600*24*2)
            wrong = int(wrong) if wrong < 50 else 50
            if random.randint(0,100) < wrong:
                raise Exception("tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed")
        print('to_background时间:', time.time() - starttime)
#         bucket.put_object_from_file('machineLearning/' + fileName, id_image_org)
#         self.write(json.dumps({"status": "success", "msg": "成功", "url": 'https://xgt2016.oss-cn-shanghai.aliyuncs.com' + '/machineLearning/' + fileName}))
        self.write(json.dumps({"status": "success", "msg": "成功", "url": "static/img/" + fileName +"_test_id_1in.png"}))

        # 删除临时文件
#         try:
#             os.remove(org_img)
#             os.remove(id_image)
#             os.remove(alpha_img)
#             os.remove(alpha_resize_img)
#             os.remove(trimap)
#             os.remove(id_image_org)
#         except:
#             pass

    def write_error(self, status_code, **kwargs):
        if kwargs['exc_info']:
            self.write(json.dumps({"status": "error", "code": status_code, "msg": repr(kwargs['exc_info'][1])}))
#             logging.error(self.request.files['crop_file'][0]['filename'] + '，' + repr(kwargs['exc_info'][1]))
        else:
            self.write(json.dumps({"status": "error", "code": status_code, "msg": kwargs['msg']}))
#             logging.error(self.request.files['crop_file'][0]['filename'] + '，' + kwargs['msg'])
